package com.igelato.utils;

import com.alibaba.fastjson2.JSON;
import com.igelato.model.AdminUser;
import com.igelato.response.AppException;
import com.igelato.response.ErrorCodeMsgEnum;
import okhttp3.*;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * @Description: 各种工具类
 * @Author: wht
 * @Date: 2023-12-30
 */
public class Tools {
//    public static String encryptPassword(String password) {
//        MessageDigest md = null;
//        try {
//            md = MessageDigest.getInstance("SHA-256");
//        } catch (NoSuchAlgorithmException e) {
//            throw new AppException(ErrorCodeMsgEnum.SERVICE_ERROR);
//        }
//        md.update(password.getBytes());
//        byte[] bytes = md.digest();
//        StringBuilder sb = new StringBuilder();
//        for (byte b : bytes) {
//            sb.append(String.format("%02x", b));
//        }
//        return sb.toString();
//    }
//
//    public static String getInitPwd() {
//        AdminUser user = ThreadLocalTool.getUser();
//        String mobile = user.getMobile();
//        String password = encryptPassword("Igelato" + mobile.substring(7));
//        return password;
//    }


    public static Object httpGet(String url) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).get().build();
        try (Response response = client.newCall(request).execute()) {
            String res = response.body().string();
            return JSON.parse(res);
        } catch (Exception e) {
            throw new AppException(ErrorCodeMsgEnum.SERVICE_ERROR);
        }
    }

    public static Object httpPost(String url, Map body) {
        try {
            MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
            OkHttpClient client = new OkHttpClient();

            RequestBody requestBody = RequestBody.create(JSON_TYPE, JSON.toJSONString(body));
            Request request = new Request.Builder().url(url).post(requestBody).build();
            Response response = client.newCall(request).execute();
            String res = response.body().string();
            return JSON.parse(res);
        } catch (Exception e) {
            throw new AppException(ErrorCodeMsgEnum.SERVICE_ERROR);
        }
    }
}
